﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ControlesExtendidos
{
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:ServerControl1 runat=server></{0}:ServerControl1>")]
    public class DropDownListExtendido : DropDownList
    {
        bool dataBinding = false;
        string cachedSelectedValue;
        public override string SelectedValue
        {
            get
            {
                return base.SelectedValue;
            }
            set
            {
                if (dataBinding)
                {
                    cachedSelectedValue = value;
                    base.SelectedValue = null;
                }
                else
                {
                    base.SelectedValue = value;
                }
            }
        }
        protected override void OnDataBinding(EventArgs e)
        {
            dataBinding = true;
            try
            {
                base.OnDataBinding(e);
            }
            finally
            {
                dataBinding = false;
            }
            if (cachedSelectedValue != null)
                BeforeSelect(cachedSelectedValue);
            SelectedValue = cachedSelectedValue;
        }
        protected virtual void BeforeSelect(string valueToBeSelected)
        {
            ListItem item = Items.FindByValue(valueToBeSelected);
            if (null == item)
                Items.Add(valueToBeSelected);
        }
    }
}

